package com.items.form.base;

import com.items.form.model.Page;
import com.items.form.model.TFormTable;
import com.items.form.mapper.TFormTableMapper;
import com.items.form.mapper.TFormValueMapper;
import com.items.form.model.TFormValue;
import com.items.form.model.TableBase;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 动态基础服务impl
 * 所有service都可以继承，自带基础的curd操作，查询条件只支持全等
 *
 * @author bai
 * @date 2023/02/08
 */
public class DynamicBaseServiceImpl<E extends TableBase> extends AbsDynamicService<E> implements IDynamicBaseService<E> {

    private final TFormTableMapper tFormTableMapper;

    private final TFormValueMapper tFormValueMapper;

    public DynamicBaseServiceImpl(String tableName, Class<E> tClass, TFormTableMapper tFormTableMapper, TFormValueMapper tFormValueMapper) {
        super(tableName, tClass);
        this.tFormTableMapper = tFormTableMapper;
        this.tFormValueMapper = tFormValueMapper;
//        this.init();
    }

    public void init(){
        List<TFormTable> formTables = tFormTableMapper.selectList(new LambdaQueryWrapper<TFormTable>().eq(TFormTable::getTableName, tableName));
        tFormTableMapper.insertOrUpdateBatch(getTableInit(formTables));
    }

    @Override
    public Boolean addFormList(E dto) {
        String rowId =  String.valueOf(tFormValueMapper.getUUid());
        try {
            dto.setRowId(rowId);
            return tFormValueMapper.insertBatch(getAddFormList(rowId, dto)) > 0;
        }catch (IllegalAccessException e){

        }
        return false;
    }

    @Override
    public Boolean addFormBatchList(List<E> list) {
        try {
            List<TFormValue> data = new ArrayList<>();
            for (E dto:list){
                String rowId =  String.valueOf(tFormValueMapper.getUUid());
                dto.setRowId(rowId);
                data.addAll(getAddFormList(rowId, dto));
            }
            return tFormValueMapper.insertBatch(data) > 0;
        } catch (IllegalAccessException e){

        }
        return false;
    }

    @Override
    public List<E> getFormList(E dto) {
        try {
            List<TFormValue> list = tFormValueMapper.getFormAllRow(tableName, objToFormValue(dto));
            return getFormList(list);
        } catch (IllegalAccessException e){

        }
        return Collections.emptyList();
    }

    @Override
    public Boolean updateFormList(E dto){
        List<TFormValue> formRow =  tFormValueMapper.getFormRow(tableName, dto.getRowId());
        try {
            return tFormValueMapper.insertOrUpdateBatch(getUpdateFormList(formRow,dto)) > 0;
        } catch (IllegalAccessException e){
            //  xxx
        }
        return false;
    }


    @Override
    public Boolean delFormRow(String rowId) {
        return tFormValueMapper.delByRowId(tableName, rowId) > 0;
    }
}
